import { Message } from "element-ui";
const urls =
  "https://compass.jinritemai.com/compass_api/shop/product_card/channel_product/channel_product_list";
const baseUrl = "http://dly.doulingyang.cn/";
const baseURLs2 = "https://fxg.jinritemai.com/";
const baseURLs3 = "https://compass.jinritemai.com/compass_api/";
const InvitationURL = "https://buyin.jinritemai.com/";
const proxyUrl = "web/webpagehttp";
let addPushUrl = [];
let reqTime = null;
let resetlodinnum = 0;
let resetlodinmax = 3;
let NoAuthorizationTime = null;
let WT_requestcp = null;
if (window.WT_request_wk) {
  WT_requestcp = window.WT_request_wk;
} else {
  setTimeout(() => {
    WT_requestcp = window.WT_request_wk;
  }, 2000);
}
let getUrlData = {};
const service = (config) => {
  return new Promise((resolve, resject) => {
    if (config.paramete) {
      const iswebserverapilist = [/\api\/*/, /\dlyadminapi\/*/];
      if (config.url.indexOf("$invitation") > -1) {
        config.url = config.url.replace("$invitation/", "");
        if (config.url.indexOf("search_feed_author") > -1) {
          let str = splitJoint(config.paramete);
          config.url += str;
          getUrlData = {
            url: `${InvitationURL}${config.url}`,
            method: config.method,
            data: JSON.stringify({
              ...config.data,
            }),
            headers: {
              Accept: "application/json, text/plain, */*",
              "Content-Type": "application/json",
            },
          };
        } else {
          if (!/\?/.test(config.url)) {
            let str = splitJoint(config.paramete);
            config.url += str;
          }
          getUrlData = {
            url: `${InvitationURL}${config.url}`,
            method: config.method,
            paramete: config.paramete,
            data: JSON.stringify({
              ...config.data,
            }),
            headers: config.headers,
          };
          if (!config.data) {
            delete getUrlData.data;
          }
        }
      } else if (
        iswebserverapilist.filter((item) => item.test(config.url)).length
      ) {
        if (config.url.split("?")[0] == "business_api") {
          if (!/\?/.test(config.url)) {
            let str = splitJoint(config.paramete);
            config.url += str;
            if (config.method == "GET" || config.method == "get") {
              config.data = undefined;
            }
          }
          getUrlData = {
            url: `https://compass.jinritemai.com/${config.url}`,
            method: config.method,
            headers: {
              "x-secsdk-csrf-request": "1",
              "x-secsdk-csrf-version": "1.2.22",
            },
            paramete: JSON.stringify(config.paramete),
          };
        } else {
          if (!/\?/.test(config.url)) {
            let str = splitJoint(config.paramete);
            config.url += str;
            if (config.method == "GET" || config.method == "get") {
              config.data = undefined;
            }
          }
          getUrlData = {
            url: `${baseUrl}${config.url}`,
            method: config.method,
            headers: {},
            data: JSON.stringify(config.data),
          };
        }
      } else if (
        config.url.split("/")[0] == "product" ||
        config.url.split("/")[0] == "common"
      ) {
        if (!/\?/.test(config.url)) {
          let str = splitJoint(config.paramete);
          config.url += str;
          if (config.method == "GET" || config.method == "get") {
            config.data = undefined;
          }
        }
        if (config.method == "get") {
          getUrlData = {
            url: `${baseURLs2}${config.url}`,
            method: config.method,
            headers: {},
            paramete: JSON.stringify(config.paramete),
          };
        } else {
          if (config.url == "product/tproduct/batchOffline") {
            getUrlData = {
              url: `${baseURLs2}${config.url}`,
              method: config.method,
              headers: config.headers,
              data: config.data,
            };
          } else {
            getUrlData = {
              url: `${baseURLs2}${config.url}`,
              method: config.method,
              headers: config.headers,
              data: JSON.stringify(config.data),
            };
          }
        }
      } else if (config.url.split("/")[0] == "shop") {
        if (!/\?/.test(config.url)) {
          let str = splitJoint(config.paramete);
          config.url += str;
          if (config.method == "GET" || config.method == "get") {
            config.data = undefined;
          }
        }
        getUrlData = {
          url: `${baseURLs3}${config.url}`,
          method: config.method,
          headers: {},
          paramete: JSON.stringify(config.paramete),
        };
      } else if (config.url.split("/")[0] == "modify_index") {
        let str = splitJoint(config.paramete);
        getUrlData = {
          withCredentials: true,
          url: `${baseURLs3}config_center/shop/modify_index${str}`,
          method: config.method,
          headers: {
            Accept: "application/json, text/plain, */*",
            "Content-Type": "application/json",
            Origin: "https://compass.jinritemai.com",
            "X-Secsdk-Csrf-Token": localStorage.getItem("Csrf"),
          },
          data: JSON.stringify(config.data),
        };
      } else if (config.url.split("/")[0] == "product_list") {
        if (!/\?/.test(config.url)) {
          let str = splitJoint(config.paramete);
          config.url += str;
          if (config.method == "GET" || config.method == "get") {
            config.data = undefined;
          }
        }
        getUrlData = {
          url: `${baseURLs2}/compass_api/shop/product/${config.url}`,
          method: config.method,
          headers: {},
          paramete: JSON.stringify(config.paramete),
        };
      } else {
        getUrlData = {
          url: `${baseUrl}${proxyUrl}`,
          method: "post",
          data: JSON.stringify({
            url: urls,
            method: config.method,
            query: config.paramete,
          }),
          headers: {},
        };
      }
      if (
        config.url.indexOf("square_pc_api/square") == -1 &&
        config.url.indexOf("connection/pc") == -1
      ) {
        getUrlData.headers.Authorization = `Bearer ${localStorage.getItem(
          "Authorization"
        )}`;
      }
      if (WT_requestcp) {
        WT_requestcp(getUrlData).then((res) => {
          console.log("请求返回的结果", res);
          let a = res.responseHeaders.split("r");
          let b = a[a.length - 1].split(",");
          if (b[1]) {
            localStorage.setItem("Csrf", b[1]);
          }
          if (res.readyState === 4 && res.status === 200 && res.responseText) {
            try {
              const getSchearData = JSON.parse(res.responseText);
              if (getSchearData.code === 0 || getSchearData.st === 0) {
                if (getSchearData.data?.code === 4390) {
                  Message.error(getSchearData.data.msg);
                  // 用户未授权
                  if (NoAuthorizationTime) {
                    clearTimeout(NoAuthorizationTime);
                    NoAuthorizationTime = null;
                  }
                  NoAuthorizationTime = setTimeout((_) => {
                    const poenclu = document.querySelectorAll(
                      '[aria-labelledby*="rcDialogTitle"]'
                    );
                    if (poenclu && poenclu.length) {
                      poenclu.forEach((elmitem) => {
                        elmitem && elmitem.click && elmitem.click();
                      });
                    }
                  }, 500);
                  resject(getSchearData);
                  return;
                } else if (getSchearData.data?.code === 4388) {
                  localStorage.setItem("loginstatus", true);
                  resject(getSchearData);
                  localStorage.removeItem("wtshopuser");
                  location.reload();
                  // 用户未购买
                  if (NoAuthorizationTime) {
                    clearTimeout(NoAuthorizationTime);
                    NoAuthorizationTime = null;
                  }
                  NoAuthorizationTime = setTimeout((_) => {
                    const poenclu = document.querySelectorAll(
                      '[aria-labelledby*="rcDialogTitle"]'
                    );
                    if (poenclu && poenclu.length) {
                      poenclu.forEach((elmitem) => {
                        elmitem && elmitem.click && elmitem.click();
                      });
                    }
                  }, 500);

                  resject(getSchearData);
                  return;
                }
                resolve(getSchearData);
              } else {
                if (getSchearData.st == 10012) {
                  localStorage.setItem("loginstatus", false);
                } else {
                  localStorage.setItem("loginstatus", true);
                }
                if (getSchearData.code === "10008") {
                  resolve(getSchearData);
                  resject(getSchearData);
                  addPushUrl.push({ rt: resolve, config: config });
                  if (reqTime) {
                    clearTimeout(reqTime);
                    reqTime = null;
                  }
                  reqTime = setTimeout((_) => {
                    clearTimeout(reqTime);
                    reqTime = null;
                    // 调用登录
                    resetlodinnum++;
                    if (resetlodinnum >= resetlodinmax) {
                      resject("重试失效");
                      addPushUrl = [];
                      resetlodinnum = 0;
                      return;
                    }
                  }, 100);
                  return;
                }
                resject(getSchearData);
              }
              return;
            } catch (error) {
              console.log(config, "1111");
              resject(error);
              let { url } = config;

              if (url.indexOf("square_pc_api/square/search_feed_author") > -1) {
                Message.error(
                  "请打开并登录达人广场页面完成后，请刷新页面后重试"
                );
                return;
              }
              if (url.indexOf("square_pc_api/square/filter") > -1) {
                Message.error(
                  "请打开并登录达人广场页面完成后，请刷新页面后重试"
                );
                return;
              }
              Message.error("当前网络异常！，请刷新页面后重试");
            }
          }
        });
      } else {
        setTimeout(() => {
          service(config);
        }, 2000);
      }
    }
  });
};
function splitJoint(obj) {
  let arr = [];
  for (let key in obj) {
    arr.push(key + "=" + obj[key]);
  }
  return arr.length > 0 ? "?" + arr.join("&") : "";
}

export default service;
